﻿using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Cfg;
using NHibernate.Cfg.Loquacious;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Linq.Functions;
using NHibernate.Linq;
using System.Text.RegularExpressions;
using NHibernate.Hql.Ast;
using System.Reflection;
using System.Linq.Expressions;
using System.Collections.ObjectModel;
using NHibernate.Linq.Visitors;
using System;
using FluentNHibernate.Utils;

namespace Repositorio
{
    public class NHibernateHelper
    {
        private static ISessionFactory sessionFactory = null;

        private static ISessionFactory CreateSessionFactory(bool createDatabase)
        {
            var configuracao = Fluently.Configure()
                  .Database(MsSqlConfiguration
                  .MsSql2008
                  .ShowSql().FormatSql()
                  .ConnectionString(@"Data Source=.\sqlexpress;Initial Catalog=teste;Integrated Security=True"))
                  .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateHelper>());

            if (createDatabase)
            {
                configuracao = configuracao.ExposeConfiguration(BuildSchemaCreateDatabase);
            }
            else
            {
                configuracao = configuracao.ExposeConfiguration(BuildSchema);
            }
            var cfg = configuracao.BuildConfiguration();

            return cfg.BuildSessionFactory();
        }

        private static void BuildSchema(Configuration config)
        {
            new SchemaExport(config)
              .Create(false, false);
        }

        private static void BuildSchemaCreateDatabase(Configuration config)
        {
            new SchemaExport(config)
              .Create(false, true);
        }

        public static ISession OpenSession()
        {
            return OpenSession(false);
        }

        public static ISession OpenSession(bool createDatabase)
        {
            if (sessionFactory == null)
            {
                sessionFactory = CreateSessionFactory(createDatabase);
            }
            return sessionFactory.OpenSession();
        }

        public static void CriarBanco()
        {
            using (OpenSession(true))
            {
            }
        }
    }

}
